#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "telephoneBook.h"
#include "contactPerson.h"

struct contactPerson
{
    char *name;
    char *phone;
};

Cper *createCper(char *name, char *phone)
{
    Cper *c = (Cper *)malloc(sizeof(Cper));
    if (NULL == c)
    {
        perror("malloc error!\n");
        return NULL;
    }

    c->name = strdup(name);
    c->phone = strdup(phone);

    return c;
}

void *Create(char *name, char *phone)
{
    return createCper(name,phone);
}

void freeCp(elementType ptr)
{
    Cper *c = (Cper *)ptr;

    free(c->name);
    free(c->phone);

    free(c);
}

void printCper(elementType ptr)
{
    Cper *c = (Cper *)ptr;

    printf("姓名: %s  号码: %s\n", c->name, c->phone);
}

bool isNameEqual(elementType ptr1, elementType ptr2)
{
    Cper *c = (Cper *)ptr1;
    char *name = (char *)ptr2;

    return strcmp(c->name, name) == 0;
}

bool isPhoneEqual(elementType ptr1, elementType ptr2)
{
    Cper *c = (Cper *)ptr1;
    char *phone = (char *)ptr2;

    return strcmp(c->phone, phone) == 0;
}

bool isNameContaining(elementType ptr1, elementType ptr2)
{
    Cper *c = (Cper *)ptr1;
    char *subname = (char *)ptr2;

    return strstr(c->name, subname) != NULL;
}

bool isPhoneContaining(elementType ptr1, elementType ptr2)
{
    Cper *c = (Cper *)ptr1;
    char *subphone = (char *)ptr2;

    return strstr(c->phone, subphone) != NULL;
}

bool sortByName(void *ptr1, void *ptr2)
{
    Cper *s1 = (Cper *)ptr1;
    Cper *s2 = (Cper *)ptr2;

    return strcmp(s1->name, s2->name) > 0;
}

bool sortByPhone(void *ptr1, void *ptr2)
{
    Cper *s1 = (Cper *)ptr1;
    Cper *s2 = (Cper *)ptr2;

    return strcmp(s1->phone, s2->phone) > 0;
}

int serachByName(void *ptr1, void *ptr2)
{
    Cper *s1 = (Cper *)ptr1;
    char *name = (char *)ptr2;

    return strcmp(s1->name, name);
}

int serachByPhone(void *ptr1, void *ptr2)
{
    Cper *s1 = (Cper *)ptr1;
    char *phone = (char *)ptr2;

    return strcmp(s1->phone, phone);
}

void modifyContact(TBook *a, elementType findElement, elementType modifyElementName, elementType modifyElementPhone)
{
    Cper *foundPerson = (Cper *)findContactPerson(a, findElement, isNameEqual);

    if (foundPerson != NULL)
    {
        free(foundPerson->phone);

        foundPerson->name = strdup((char *)modifyElementName);
        foundPerson->phone = strdup((char *)modifyElementPhone);
    }
}

char *GetInfo(void *ptr)
{
    Cper *p = (Cper *)ptr;
    //格式化输入到字符串中
    char s[256] = {0};
    sprintf(s, "name=%s telephone=%s\n", p->name, p->phone);
    return strdup(s);
}
